//
//  CommitsViewController.swift
//  Git@OSC
//
//  Created by AeternChan on 9/11/15.
//  Copyright (c) 2015 oschina. All rights reserved.
//

import UIKit
import ReactiveCocoa

class CommitsViewController: UITableViewController {
    
    var viewModel: CommitsViewModel!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
        
        viewModel.page.producer
            .filter { $0 > 0 }
            .start {
                data in
                self.tableView.reloadData()
            }
        
        viewModel.fetchCommits()
    }
    

    // MARK: - Table view data source

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.commits.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("CommitCell", forIndexPath: indexPath) as! CommitCell
        
        cell.entity = viewModel.commits[indexPath.row]
        
        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let indexPath = tableView.indexPathForSelectedRow
        let commitVC = segue.destinationViewController as! CommitViewController
        
        commitVC.viewModel = viewModel.commitViewModel(indexPath!)
    }

}
